#include "comm.h"

int main(int argc, char **argv)
{
    int msqid = create_msq();
	struct msqid_ds info;
    struct MsgType *msg = NULL;
    int timeout=0,i = 0,flag = 0 ;

    if(msqid < 0){
        return -1 ;
    }

	msg = malloc(sizeof(struct MsgType));
	sleep(2);
	printf("\n");

	while(i < atoi(argv[1]))
	{
		flag = msgctl( msqid, IPC_STAT, &info) ;
		if ( flag == -1 )
		{
			perror("msgctl() error") ;
			return -1 ;
		}

		if(info.msg_qnum != 0)
		{
			timeout = 0;			
			msg->len = -1;
			memset(msg->buf, 0, MAXSIZE);
			msg->x = ' ';
			msg->y = -1;
	 
			/* getting a message */
			if (msgrcv(msqid, (char*)msg, sizeof(struct MsgType),0,0) == -1) 
			{
				perror("msgrcv() error");
				return -1 ;
			}
			memset(&info, 0, sizeof(struct msqid_ds));
			flag = msgctl( msqid, IPC_STAT, &info) ;
			if ( flag == -1 )
			{
				perror("msgctl() error") ;
				return -1 ;
			}
			//printf("msg_qbytes =%d bytes\n",(int)info.msg_qbytes);
			//printf("msgsnd_pid = %d \n",info.msg_lspid);
			//printf("msgrcv_pid = %d \n",info.msg_lrpid);
			printf("[SERVER] pid=%d, msg->len = %d, msg->x = %c, msg->y = %d msgsnd_pid = %s\n",(int)getpid(), msg->len, msg->x, msg->y, msg->buf);
			sleep(1);
			i++;
		}
		else
		{
			printf("waiting msq %ds\r\n",5 - timeout);
			timeout++;
			sleep(1);
			if(timeout==5)
			{
				printf("waiting msq %ds\r\n",5 - timeout);
				goto msqexit;
			}
		}
	}
msqexit:
	//destroy_msq(msqid);
	free(msg);
	printf("msgrcv %d msqs finished\r\n",i);
	return 0;
}